package com.gary.shiro.service;

import com.gary.shiro.dao.OrderDAO;
import com.gary.shiro.po.Order;
import com.gary.shiro.redis.RedisLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * (Order)表服务接口
 *
 * @author gary
 * @since 2022-04-19
 */
@Service
public class OrderService {
    @Resource
    private OrderDAO orderDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 新增
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer buy() {
        RedisLock redisLock = new RedisLock("order", redisTemplate);
        Boolean isLock = redisLock.tryLock(20L);
        if (!isLock) {
            return 0;
        }
        try {
            TimeUnit.SECONDS.sleep(20);
            Integer id = 1;
            Order order = orderDao.selectByPrimaryKey(id);
            Integer count = order.getCount();
            if (order.getCount() > 0) {
                order.setCount(count - 1);
            }
            return orderDao.updateByPrimaryKey(order);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisLock.unLock();
        }
        return 0;
    }

    public Integer add() {
        Order order = new Order();
        order.setCount(515);
        int i = orderDao.insertSelective(order);
        System.out.println(order);
        return i;
    }

    static class CONSTANT {
        public static final String ORDER_BY = "create_time desc";
    }
}

